package com.usefullc.english.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usefullc.common.enums.YesNoEnum;
import com.usefullc.common.util.BeanUtils;
import com.usefullc.english.domain.ContentLike;
import com.usefullc.english.mapper.ContentLikeMapper;
import com.usefullc.english.query.ContentLikeQuery;
import com.usefullc.english.vo.ContentLikeVo;
import com.usefullc.system.entity.Pager;
import com.usefullc.system.service.AbstractBizService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 内容点赞服务类
 * @author: 星空
 * @date: 2022-08-07
 */
@Service
public class ContentLikeService extends AbstractBizService<ContentLikeMapper, ContentLike, ContentLikeQuery> {


    @Override
    protected QueryWrapper<ContentLike> getQueryWrapper(ContentLikeQuery query) {
        QueryWrapper<ContentLike> queryWrapper = super.getQueryWrapper(query);
        return queryWrapper;
    }

    public Pager<ContentLikeVo> findVoByPage(ContentLikeQuery query){
        Pager<ContentLike> page = this.findByPage(query);
        Pager<ContentLikeVo> newPage = new Pager<>(page);
        List<ContentLike> dataList = page.getDataList();
        List<ContentLikeVo> newDataList = new ArrayList<>();
        newPage.setDataList(newDataList);
        for (ContentLike contentLike : dataList) {
            ContentLikeVo contentLikeVo = BeanUtils.beanCopy(contentLike, ContentLikeVo.class);
            newDataList.add(contentLikeVo);
        }
        return newPage;
    }

    public boolean like(Long contentId,Long userId,String ip){
        ContentLike contentLike = new ContentLike();
        contentLike.setContentId(contentId);
        contentLike.setUserId(userId);
        contentLike.setIp(ip);
        contentLike.setStatus(YesNoEnum.YES.getCode());
        try{
            return this.save(contentLike);
        }catch (Exception e){
            //修改
            ContentLikeQuery contentLikeQuery = new ContentLikeQuery();
            contentLikeQuery.setContentId(contentId);
            contentLikeQuery.setUserId(userId);
            ContentLike entity = this.findOne(contentLikeQuery);
            entity.setStatus(YesNoEnum.YES.getCode());
            return this.update(entity);
        }
    }

    public boolean unLike(Long contentId,Long userId){
        ContentLikeQuery contentLikeQuery = new ContentLikeQuery();
        contentLikeQuery.setContentId(contentId);
        contentLikeQuery.setUserId(userId);
        ContentLike entity = this.findOne(contentLikeQuery);
        entity.setStatus(YesNoEnum.NO.getCode());
        return this.update(entity);
    }

}
